package com.shgsh.common.repository;

import com.lovver.ssdbj.pool.SSDBDataSource;
import com.lovver.ssdbj.pool.SSDBPoolConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


/**
 * SSDB连接和关闭
 * SSDB与线程绑定 一个线程一个连接
 * Created by jessy on 2015/8/4.
 */
@Repository("basicRepository")
public class BasicRepository {

    Logger logger = LoggerFactory.getLogger(BasicRepository.class);

    @Autowired
    SSDBDataSource ssdbDataSource;

    private static ThreadLocal<SSDBPoolConnection> conn = new ThreadLocal<>();

    /**
     *
     * 数据库连接初始化
     * */
    public  SSDBPoolConnection init(){
        SSDBPoolConnection connection = conn.get();
        if(connection == null){
            try {
                connection = ssdbDataSource.getConnection();
                conn.set(connection);
                logger.debug("database connect success.");
                return connection;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 关闭数据库连接
     */
    public void closeConnect(){
        SSDBPoolConnection connection = conn.get();
        if (connection != null){
            logger.debug("database close success.");
            connection.close();
        }
        conn.set(null);
    }

}
